import router from "../router";
import axios from "axios";
import { useMessage } from "naive-ui";
import { useRouter } from "vue-router";
let prefix = "https://duxinggj.com/";
//let prefix = "http://127.0.0.1:8360/";
/**
 * 格式化日期
 * @param t 时间戳
 * @returns
 */
export function transferTimeYMDHm(t) {
  const time = new Date(t ? t : new Date().getTime());
  const Year = time.getFullYear(),
    Month = time.getMonth() + 1,
    Data = time.getDate() < 10 ? 0 + "" + time.getDate() : time.getDate(),
    hour = time.getHours() < 10 ? 0 + "" + time.getHours() : time.getHours(),
    Minutes =
      time.getMinutes() < 10 ? 0 + "" + time.getMinutes() : time.getMinutes(),
    Seconds =
      time.getSeconds() < 10 ? 0 + "" + time.getSeconds() : time.getSeconds();
  var myddy = time.getDay(); //获取存储当前日期
  var weekday = [
    "星期日",
    "星期一",
    "星期二",
    "星期三",
    "星期四",
    "星期五",
    "星期六",
  ];
  return `${Year}-${Month}-${Data}- ${hour}:${Minutes}:${Seconds} ${weekday[myddy]}`;
}
export function transferTimeYMD(t: string) {
  const time = new Date(t ? t : new Date().getTime());
  const Year = time.getFullYear(),
    Month = time.getMonth() + 1,
    Data = time.getDate() < 10 ? 0 + "" + time.getDate() : time.getDate();
  return `${Year}-${Month}-${Data} `;
}

/**
 * 路由跳转
 * @param url 跳转地址
 * @param cu 额外的参数
 */
export function hf(url: string, cu?: any) {
  router.push({
    path: url,
    query: cu,
  });
}
/**
 * post请求
 * @param url  接口地址
 * @param data 参数
 * @returns
 */
export function dxpost(url: string, data: any, method?: any) {
  const message = useMessage();
  if (!data) {
    data = {};
  }
  if (!data["id"]) {
    delete data["id"];
  }
  return new Promise((resolve) => {
    axios({
      method: method || "post",
      url: prefix + url,
      headers: {
        token: localStorage.token,
      },
      data: data,
    })
      .then((res) => {
        if (res.data.errno != 0) {
          window.$message.destroyAll();
          window.$message.error(res.data.errmsg);
        }
        if (res.data.errno == -2) {
          localStorage.clear();
          router.push({
            path: "login",
          });
          return;
        }
        resolve(res.data);
      })
      .catch((res) => {
        const ress = "" + res;
        window.$message.destroyAll();
        window.$message.error(res.errmsg);
        console.log("错误");
        resolve(ress);
      });
  });
}

/**
 * get请求
 * @param url 接口地址
 * @param data 参数
 * @returns
 */
export function dxget(url: string, data?: any) {
  let urls = prefix + url;
  if (url.indexOf("http") >= 0) {
    urls = url;
  }

  return new Promise((resolve) => {
    axios
      .get(urls, {
        params: data,
        headers: {
          token: localStorage.token,
        },
      })
      .then(async function (response) {
        if (response.data.errno != 0) {
          window.$message.destroyAll();
          window.$message.error(response.data.errmsg);
        }
        if (response.data.errno == -2) {
          localStorage.clear();
          router.push({
            path: "login",
          });
          return;
        }
        resolve(response.data);
      })
      .catch((res) => {
        const ress = "" + res;
        window.$message.destroyAll();
        window.$message.error(res.errmsg);
        resolve(ress);
      });
  });
}

/**
 * del
 * @param url 接口地址
 * @param data 参数
 * @returns
 */
export function dxdel(url: string, data: any) {
  window.$message.destroyAll();
  let urls = prefix + url;
  if (url.indexOf("http") >= 0) {
    urls = url;
  }
  return new Promise((resolve) => {
    axios
      .delete(urls, {
        params: data,
        headers: {
          token: localStorage.token,
        },
      })
      .then(function (response) {
        if (response.data.errno != 0) {
          window.$message.error(response.data.errmsg);
        }
        if (response.data.errno == -2) {
          localStorage.clear();
          router.push({
            path: "login",
          });
          return;
        }
        resolve(response.data);
      })
      .catch((res) => {
        const ress = "" + res;
        window.$message.error(res.errmsg);
        resolve(ress);
      });
  });
}

/**
 * 逗号金额转金额
 * @param buyTotal 带逗号的金额 如 10,000,000
 * @returns
 */
export function CommaTransferAmount(buyTotal) {
  const jiner = parseFloat(buyTotal.replace(new RegExp(",", "g"), ""));
  return (jiner / 100000000).toFixed(2);
}

/**
 * 滚动到底部监听
 * @param className  class名称
 * @param fun 滚动到底部的回调方法
 */
export function bottomMonitor(className, fun) {
  new IntersectionObserver((entries) => {
    let item = entries[0]; // 拿第一个就行，反正只有一个
    if (item.isIntersecting) {
      fun();
      console.log("滚动到了底部，开始请求数据");
    }
  }).observe(document.querySelector("." + className)); // 监听参照元素
}
/**
 * 获取路由后面的参数
 * @returns
 */
export const qurl = () => {
  const { currentRoute } = useRouter();
  const qurl = currentRoute.value.query;
  return qurl;
};
/**
 * 股票代码转换
 * @param code 股票代码
 * @returns
 */
export function getCodesd(code) {
  const colum = "" + code.substr(0, 3);
  let text = 0;
  switch (colum) {
    case "000":
    case "001":
    case "002":
    case "003":
    case "300":
    case "301":
      text = 0;
      break;
    case "600":
    case "601":
    case "603":
    case "605":
    case "688":
      text = 1;
      break;
  }
  return text + "." + code;
}
/**
 * 金额转换成 亿单位
 * @param val
 * @returns
 */
export const MU = (val) => {
  let fixexs = (val / 100000000).toFixed(2);
  if (fixexs == "NaN") {
    fixexs = "-";
  }
  return fixexs + "亿";
};
/**
 * 保留两位小数
 * @param val
 * @returns
 */
export const toFixed = (val) => {
  return val.toFixed(2);
};
/**
 * 金额转换成万单位
 * @param val
 * @returns
 */
export const AU = (val) => {
  let fixexs = (val / 10000).toFixed(2);
  if (fixexs == "NaN") {
    fixexs = "-";
  }
  return fixexs + "万";
};
/**
 * 设置颜色  条件为真显示红色
 */
export const setColour = (val) => {
  return val ? "red" : "ls";
};

export const dialog = (content) => {
  return new Promise((resolve) => {
    window.$useDialog.warning({
      title: "警告",
      content: content,
      positiveText: "确定",
      negativeText: "取消",
      onPositiveClick: () => {
        resolve(1);
      },
    });
  });
};

/**
 * 添加到观察区
 * @param scode  股票代码
 * @param laiyuan  来源
 * @param text 额外参数 json格式的字符串
 */
export const addGuanca = async (scode, laiyuan, text) => {
  /*获取诊断结果*/
  const jhbjse = [];
  const stockdiagnosis: any = await dxget("dc/stockdiagnosis", {
    code: scode,
    type: 1,
  });
  jhbjse.push(stockdiagnosis.data);

  const stockdiagnosisbb: any = await dxget("dc/stockdiagnosis", {
    code: scode,
    type: 2,
  });
  jhbjse.push(stockdiagnosisbb.data);

  const stockdiagnosiscc: any = await dxget("dc/stockdiagnosis", {
    code: scode,
    type: 3,
  });
  jhbjse.push(stockdiagnosiscc.data);

  const stockdiagnosisdd: any = await dxget("dc/stockdiagnosis", {
    code: scode,
    type: 4,
  });
  jhbjse.push(stockdiagnosisdd.data);
  /*end*/

  const resData: any = await dxget("gupiao/getJiage", {
    scode: scode,
  });
  const res = {
    observetype: "",
    code: "" + scode,
    name: resData.data.f58,
    parameter: JSON.stringify(text),
    record: JSON.stringify({
      secCode: resData.data.f57,
      price: resData.data.f19,
      announcementTime: new Date().getTime(),
      laiyuan: laiyuan,
      extra: JSON.stringify(resData.data),
      zd: JSON.stringify(jhbjse),
    }),
  };
  if (text.observetype) {
    res.observetype = text.observetype;
  }
  const { errno, data }: any = await dxpost("gupiao/addCode", res);
  if (errno == 0) {
    window.$message.success(data.msgText);
  }
};
